package com.drojian.demo4.internet;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import com.drojian.demo.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class JsonActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn1;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.part4_activity_json);
        btn1 = findViewById(R.id.btn1);
        textView = findViewById(R.id.json_View);
        btn1.setOnClickListener(this);
    }

    public StringBuilder parseJson() {
        try (InputStream file = getAssets().open("data1.json");
             BufferedReader reader = new BufferedReader(new InputStreamReader(file))) {
            StringBuilder jsonString = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonString.append(line);
            }

            JSONArray array = new JSONArray(jsonString.toString());
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < array.length(); i++) {
                JSONObject jsonObject = array.getJSONObject(i);
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");
                String age = jsonObject.getString("age");
                result.append("id :").append(id).append("  name :").append(name).append("  age :").append(age).append("\n");
            }
            return result;

        } catch (Exception e) {
            throw new RuntimeException("IO Exception occurred", e);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn1: {
                StringBuilder builder = parseJson();
                textView.setText(builder);
                break;
            }
        }
    }
}